package com.dkm.modules.sys.auth.controller;

import com.dkm.commons.BaseController;
import com.dkm.commons.Response;
import com.dkm.constant.CacheConstant;
import com.dkm.constant.Constant;
import com.dkm.modules.sys.auth.model.ChangePwdForm;
import com.dkm.modules.sys.operator.model.OperatorSelect;
import com.dkm.modules.sys.role.service.RoleService;
import com.dkm.modules.sys.user.service.UserService;
import com.dkm.modules.wx.login.model.LoginForm;
import com.dkm.util.redis.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @ClassName AuthController
 * @Description: 运营端登录
 * @Author 杨膑
 * @Date 2019/9/10
 * @Version V1.0
 **/

@RestController
@Api(tags = {"A1 运营端 登录-登出"})
public class AuthController extends BaseController {


    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;
    @Value("${remote.prefix}")
    private String tokenPrefix;

    @Autowired
    private RoleService roleService;

    /**
     * 登录
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Response login(@Valid @ApiParam(value = "登录数据", required = true) LoginForm form) {
        return userService.signIn(form, getSession(), Constant.LOGIN_TYPE_NOT_OPERATOR);
    }

    @PostMapping("/loginOut")
    @ApiOperation("退出登录")
    public Response loginout(HttpServletRequest request) {
        //获取token
        String token = request.getHeader(Constant.USER_TOKEN);
        //从redis中删除token
        String key = tokenPrefix + token;
        String userName = redisUtils.get(key);
        redisUtils.delete(CacheConstant.User.PREFIX_NAME + userName);

        redisUtils.delete(key);
        return Response.ok();
    }

    @PostMapping("/changePwd")
    @ApiOperation("修改密码")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response changePwd(@ApiParam("修改密码数据") @RequestBody ChangePwdForm c) {
        //更新密码
        return userService.changePwd(c.getPassword(), c.getNewPassword(), getUserNm());
    }

    @GetMapping("/getDataScopeList")
    @ApiOperation("获取数据权限下拉数据")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response getDataScopeList() {
        List<OperatorSelect> dataScopeList = userService.getUserScope(getUserNm());
        return Response.ok(dataScopeList);
    }
}
